﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBTool
{
    class IniFile
    {
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);

        private string filePath;

        public IniFile(string iniFilePath)
        {
            filePath = iniFilePath;
        }

        public string ReadValue(string pSection, string pKey, string pDefault)
        {
            return (z_GetString(pSection, pKey, pDefault));
        }

        public string ReadValue(string pSection, string pKey)
        {
            return (z_GetString(pSection, pKey, ""));
        }

        public void WriteValue(string pSection, string pKey, string pValue)
        {
            WritePrivateProfileString(pSection, pKey, pValue, filePath);
        }

        private string z_GetString(string pSection, string pKey, string pDefault)
        {
            string sRet = pDefault; byte[] bRet = new byte[255];
            int i = GetPrivateProfileString(pSection, pKey, pDefault, bRet, 255, filePath);
            sRet = System.Text.Encoding.GetEncoding(1252).GetString(bRet, 0, i).TrimEnd((char)0);

            return (sRet);
        }
    }
}
